package com.hl.order.controller;





import com.hl.order.domain.User;
import com.hl.order.service.IUserService;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RemoteUserService remoteUserService;

    @RequestMapping("/toLogin")
    public R toLogin(@RequestBody User user){
        System.out.println(user);

//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username",user.getUserName());
//        queryWrapper.eq("password",user.getUserPassword());
        User user1 = userService.selectUserByUsernameAndPassword(user.getUserName(), user.getUserPassword());
        //校验用户名和密码是否匹配
        if(user1 == null){
            return R.fail("登录失败！");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user1.getUserId().longValue()); //强转
        sysUser.setUserName(user1.getUserName());
        LoginUser loginUser1 = new LoginUser();
        loginUser1.setUsername(user1.getUserName());
        loginUser1.setUserid(user1.getUserId().longValue());
        loginUser1.setSysUser(sysUser);
        //匹配登录成功，返回token给前端，同时保存用户信息到redis中
        return R.ok(tokenService.createToken(loginUser1));
    }

    @RequestMapping("/info")
    public R info(@RequestHeader(required = false) String authorization){
        //解析token，得到用户信息
        Claims claims = JwtUtils.parseToken(authorization);
        //得到用户id.到数据库表中查询实时数据，返回给前端
        Integer id = (Integer) claims.get("user_id");
        //到数据库中查询
        User user = userService.selectUserByUserId(id);
        return R.ok(user);
    }


}

